﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.Samples.WindowsPhoneCloud.StorageClient
Imports System.Windows.Threading
Imports System.Globalization

Namespace ViewModel

    Friend Enum TableAction
        None = 0
        Create = 1
        Delete = 2
    End Enum

	Public Class TablesPageViewModel
        Inherits TableBaseViewModel(Of TableServiceSchema)
        Private Const IconsRootUri As String = "/Toolkit.Content/"

        Private action As TableAction = TableAction.None
        Private currentTable As TableServiceSchema = Nothing

        Public Sub New()
            Me.New(App.CloudClientFactory, Deployment.Current.Dispatcher)
        End Sub

        Public Sub New(ByVal cloudClientFactory As ICloudClientFactory, ByVal dispatcher As Dispatcher)
            MyBase.New(cloudClientFactory, dispatcher)
        End Sub

        Public Overrides ReadOnly Property TableName() As String
            Get
                Return "Tables"
            End Get
        End Property

        Public Sub NewTable()
            Dim newTableName = String.Format(CultureInfo.InvariantCulture, "Table{0}", Date.Now.ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture))
            Me.currentTable = New TableServiceSchema(newTableName)
            Me.action = TableAction.Create

            Me.Message = "Creating new table..."
            Me.IsLoading = True

            Try
                Me.Context.AddTable(Me.currentTable)
                Me.Context.BeginSaveChanges(AddressOf Me.OnBeginSaveChanges, Nothing)
            Catch exception As Exception
                Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message

                Me.IsLoading = False
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage)
            End Try
        End Sub

        Public Sub DeleteTable(ByVal table As TableServiceSchema)
            Me.currentTable = table
            Me.action = TableAction.Delete

            Me.Message = "Deleting table..."
            Me.IsLoading = True

            Try
                ' In the case the table was previously detached in a failed operation.
                If Not Me.Context.Entities.Any(Function(e) e.Entity Is Me.currentTable) Then
                    Me.Context.AttachTo("Tables", Me.currentTable)
                End If

                Me.Context.DeleteObject(Me.currentTable)
                Me.Context.BeginSaveChanges(AddressOf Me.OnBeginSaveChanges, Nothing)
            Catch exception As Exception
                Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message

                Me.IsLoading = False
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage)
            End Try

        End Sub

        Public Sub OnBeginSaveChanges(ByVal asyncResult As IAsyncResult)
            Me.Dispatcher.BeginInvoke(
                Sub()
                    Try
                        Me.Context.EndSaveChanges(asyncResult)

                        ' Update the Table collection that is binded in the page.
                        If Me.action = TableAction.Create Then
                            Me.Table.Add(Me.currentTable)
                        ElseIf Me.action = TableAction.Delete Then
                            Me.Table.Remove(Me.currentTable)
                        End If

                        Me.Message = "Changes saved successfully."
                    Catch exception As Exception
                        Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", StorageClientExceptionParser.ParseDataServiceException(exception).Message)

                        ' Detach from the Context the table that produced the failed operation.
                        Me.Context.Detach(Me.currentTable)
                    Finally
                        Me.IsLoading = False
                    End Try
                End Sub)
        End Sub

        Protected Overrides Sub PopulateApplicationBarButtons(ByVal applicationBar As IApplicationBar)
            Dim refreshButton = New ApplicationBarIconButton(New Uri(String.Format(CultureInfo.InvariantCulture, "{0}{1}", IconsRootUri, "appbar.refresh.rest.png"), UriKind.Relative)) With {.Text = "Refresh"}
            AddHandler refreshButton.Click, Sub(s, e) Me.LoadTable()

            Dim addButton = New ApplicationBarIconButton(New Uri(String.Format(CultureInfo.InvariantCulture, "{0}{1}", IconsRootUri, "appbar.add.rest.png"), UriKind.Relative)) With {.Text = "add table"}
            AddHandler addButton.Click, Sub(s, e) Me.NewTable()

            applicationBar.Buttons.Add(refreshButton)
            applicationBar.Buttons.Add(addButton)
        End Sub
    End Class
End Namespace